<?php
namespace App\Http\Classes;
use Illuminate\Support\Facades\DB;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/7/3 0003
 * Time: 上午 9:09
 */
class User
{
    private $table = 'users';
    private $db;
    private $userId = null;

    public function __construct($userId = null)
    {
        $this->db = DB::table($this->table);
        if ($userId !== null)
        {
            $this ->userId = $userId;
            $this ->db = $this ->db->where('userId', '=', $this->userId);
        }
    }

    public function login(array $data)
    {
        if ( isset($data['username']) && isset($data['password']) && isset($data['rule']))
        {
            $user = $this->db->where('userName', '=', $data['username'])
                ->where('password', '=', hash('md5', $data['password']))
                ->where('rule', '=', $data['rule']);
            $result = $user->select('userId')->get();
            //dd($result);
            if ( $result != null )
            {
                $token = hash('md5', User::getRand());
                $user =  $user->update(['token' => $token]);
                $res = [];
                $res['userId'] = $result[0]->userId;
                $res['token'] = $token;
                return $res;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return null;
        }
    }

    public function tokenVerify($token)
    {
        //dd($token);
        $result = $this->db->where('token', '=', $token)->count();
//        dd($result);
        if ( $result >= 1 )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public function updatePassword($oldPassword, $newPassword)
    {
        $user = $this->db->where('password', '=', hash('md5', $oldPassword))->count();
        if ( $user >= 1 )
        {
            $user = $this->db->update(['password' => hash('md5', $newPassword)]);
            if ( $user )
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return null;
        }
    }

    private static function getRand(){
        $length = 6;
        $min = pow(10 , ($length - 1));
        $max = pow(10, $length) - 1;
        return mt_rand($min,$max);
    }
}